package our.pack;

import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MediaVideoCameraSaveActivity extends Activity{
	
	private Button save, discard;
	private EditText editName;
	private MyPoint point;
	private static File PATH = Environment.getExternalStorageDirectory();
	private String fileName;
	private MetaDataDataSource metaDataDatasource;
	
	/**
	 * saves the video made in MediaVideoCameraActivity
	 */
	public void onCreate(Bundle SaveInstanceState){
		super.onCreate(SaveInstanceState);
		setContentView(R.layout.media_video_camera_save);
		
		//db
		metaDataDatasource = new MetaDataDataSource(this);
		metaDataDatasource.open();
		
		//get the filepath and the point where it's made
		Intent i = getIntent();
		Bundle b = i.getExtras();
		fileName = (String) b.get("PATH");
		point = (MyPoint) b.get("Point");
		
		//UI
		save = (Button) findViewById(R.id.btnSaveVideo);
		discard = (Button) findViewById(R.id.btnDiscardVideo);
		editName = (EditText) findViewById(R.id.editVideoName);
		
	
		//deletes the files if the user clicks on the delete button
		discard.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				//delete the file
				File file = new File(fileName);
				file.delete();
				finish();
			}
		});
		
		//saves the file
		save.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				
				//rename the file
				File file = new File(fileName);
				String newFileName = PATH + "/" + editName.getText().toString() + ".mp4";
				File newFile = new File(newFileName);
				file.renameTo(newFile);
				
				//set the date
				String[] ids = TimeZone.getAvailableIDs(+1 * 60 * 60 * 1000);					
				SimpleTimeZone cest = new SimpleTimeZone(+1 * 60 * 60 * 1000, ids[0]);
				Calendar cal = new GregorianCalendar(cest);
				String date = cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH)+1)  + "-" + cal.get(Calendar.YEAR);
				
				//saves it in the database
				MetaData m = metaDataDatasource.createMetaData(editName.getText().toString(),newFileName, date, "video", point);
				
				finish();
			}
		});
		
	}

}
